package com.psds.quartz;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;


/**
 * author: cjianquan
 * date: 2016/8/26
 */
@Service("commonQuartz")
public class CommonQuartz {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private QuartzLogService quartzLogService;

    /**
     * 执行任务
     * @param arguments arguments[0]任务url,arguments[1]任务名称
     */
    public void run(Object[] arguments){

        if(this.quartzLogService==null){
            this.quartzLogService = (QuartzLogService)ApplicationUtil.getBean("quartzLogService");
        }
        QuartzLogEntity quartzLog = new QuartzLogEntity();

        String url = "",taskname = "";
        if(arguments!=null && arguments.length>0){
            url = arguments[0].toString();
            taskname = arguments[1].toString();
        }
        HttpGet httpGet = new HttpGet(url);
        HttpClient http = new DefaultHttpClient();
        try {
            HttpResponse response = http.execute(httpGet);
            ByteArrayOutputStream baos   =   new   ByteArrayOutputStream();
            int   i=-1;
            InputStream is = response.getEntity().getContent();

            while((i=is.read())!=-1){
                baos.write(i);
            }
            String rtnMsg = baos.toString("utf-8");
            quartzLog.setLogTaskname(taskname);
            quartzLog.setLogExectime(new Date());
            quartzLog.setLogExecmsg(rtnMsg);
            //执行方式 1自动，2手动
            quartzLog.setLogExectype("1");

            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == 200){
                //执行结果 1成功，2失败
                log.info("调用"+url+"成功");
                Map<String,Object> rtnMap = JacksonUtil.json2Map(rtnMsg);
                boolean result = Boolean.valueOf(rtnMap.get("result").toString());
                quartzLog.setLogExecmsg(rtnMap.get("msg").toString());
                //执行结果 1成功，2失败
                quartzLog.setLogExecresult(result?"1":"2");
            }else{
                quartzLog.setLogExecresult("2");
                quartzLog.setLogExecmsg("执行失败，失败码："+statusCode);
            }
            this.quartzLogService.saveQuartzLog(quartzLog);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            quartzLog.setLogTaskname(taskname);
            quartzLog.setLogExectime(new Date());
            quartzLog.setLogExecmsg("执行异常，异常信息："+e.getMessage());
            //执行方式 1自动，2手动
            quartzLog.setLogExectype("1");
            quartzLog.setLogExecresult("2");
            this.quartzLogService.saveQuartzLog(quartzLog);
        }
    }

    /**
     * 手动执行任务
     * @param arguments  arguments[0]任务url,arguments[1]任务名称
     * @return
     */
    public boolean manualRun(Object[] arguments){
        boolean result = false;
        QuartzLogEntity quartzLog = new QuartzLogEntity();

        String url = "",taskname = "";
        if(arguments!=null && arguments.length>0){
            url = arguments[0].toString();
            taskname = arguments[1].toString();
        }
        HttpGet httpGet = new HttpGet(url);
        HttpClient http = new DefaultHttpClient();
        try {
            HttpResponse response = http.execute(httpGet);
            ByteArrayOutputStream baos   =   new   ByteArrayOutputStream();
            int   i=-1;
            InputStream is = response.getEntity().getContent();

            while((i=is.read())!=-1){
                baos.write(i);
            }
            String rtnMsg = baos.toString("utf-8");
            quartzLog.setLogTaskname(taskname);
            quartzLog.setLogExectime(new Date());
//            quartzLog.setLogExecmsg(rtnMsg);
            //执行方式 1自动，2手动
            quartzLog.setLogExectype("2");

            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == 200){
                log.info("调用"+url+"成功");
                Map<String,Object> rtnMap = JacksonUtil.json2Map(rtnMsg);
                result = Boolean.valueOf(rtnMap.get("result").toString());
                quartzLog.setLogExecmsg(rtnMap.get("msg").toString());
                //执行结果 1成功，2失败
                quartzLog.setLogExecresult(result?"1":"2");
            }else{
                //执行结果 1成功，2失败
                quartzLog.setLogExecresult("2");
                quartzLog.setLogExecmsg("执行失败，失败码："+statusCode);
            }
            this.quartzLogService.saveQuartzLog(quartzLog);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            result = false;
            quartzLog.setLogTaskname(taskname);
            quartzLog.setLogExectime(new Date());
            quartzLog.setLogExecmsg("执行异常，异常信息："+e.getMessage());
            //执行方式 1自动，2手动
            quartzLog.setLogExectype("2");
            quartzLog.setLogExecresult("2");
            this.quartzLogService.saveQuartzLog(quartzLog);
        }
        return result;
    }


}
